<template>
  <div>
    <Nav />
    <el-card>
      <div class="headTitBox">
        <div class="ht">
          <div class="ht_c">
            <img src="../../../assets/images/userIcon.png">
            <div class="ht_c_t">申请人:&nbsp;&nbsp;{{ name }}</div>
          </div>
        </div>
        <div class="ht">
          <div class="ht_c">
            <img src="../../../assets/images/phoneIcon.png">
            <div class="ht_c_t">申请人电话:&nbsp;&nbsp;{{ phone }}</div>
          </div>
        </div>
        <div class="ht">
          <div class="ht_c">
            <img src="../../../assets/images/accountIcon.png">
            <div class="ht_c_t">申请人域账号:&nbsp;&nbsp;{{ jobAccount }}</div>
          </div>
        </div>
      </div>
      <div class="form-content">
        <p>实施方案</p>
        <el-form ref="form" class="form-input" :model="formDate" :rules="ruleData" label-width="120px">
          <el-row>
            <el-form-item label="项目说明" prop="projectInstruction">
              <el-input type="textarea" v-model="formDate.projectInstruction"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="formDate.projectName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设计单位" prop="designUnit">
                <el-input v-model="formDate.designUnit"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="建设单位" prop="suggestedUnit">
                <el-input v-model="formDate.suggestedUnit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目类型" prop="projectType">
                <el-select placeholder="请选择项目类型" v-model="formDate.projectType" multiple>
                  <el-option v-for="(item, index) in projectTypeLists" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="紧急程度" prop="emergencyLevel">
                <el-select placeholder="请选择程度范围" v-model="formDate.emergencyLevel">
                  <el-option label="非常紧急" value="2"></el-option>
                  <el-option label="紧急" value="1"></el-option>
                  <el-option label="一般" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地区" prop="selectedRegions">
                <el-cascader class="select" size="large" :options="regions" v-model="formDate.selectedRegions" @change="regionChange" ref="cascaderAddr"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="beginTime">
                <el-date-picker type="datetime" class="datetime" placeholder="选择开始日期" v-model="formDate.beginTime"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="完成时间" prop="endTime">
                <el-date-picker type="datetime" class="date" placeholder="选择结束日期" v-model="formDate.endTime"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="下一流程">
                <el-input v-model="nextNodeNameContent" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下一流程人员" prop="nextAuthor">
                <el-select placeholder="请选择下一流程人员" v-model="formDate.nextAuthor" multiple @change="handleChange">
                  <el-option v-for="(item, index) in nextAuthorLists" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="formDate.remarks"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="上传">
              <el-upload ref="upfile" class="upload-demo" :http-request="fnUploadRequest" action :before-upload="beforeUpload" :show-file-list="true" :on-remove="onRemove" :file-list="fileList">
                <el-button size="small" type="primary">文件上传</el-button>
              </el-upload>
            </el-form-item>
          </el-row>

          <div class="btn-option">
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="Parent">取消</el-button>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>
<script>
import { EmbodimentCreate, getAuthorByNodeID, fileUploadFile, getAllProjectType } from '@/api/api'
import { nextNodeArr, getMultipleLabel } from '@/unils/utils'
import { regionData } from 'element-china-area-data'
import { mapGetters } from 'vuex'
import swal from 'sweetalert'
import _ from 'underscore'
import nav from "@/components/navigation"
export default {
  components: {
    Nav: nav
  },
  data () {
    var checkEndTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择结束日期'))
      } else if (this.formDate.beginTime) {
        if (new Date(this.formDate.beginTime) > new Date(value)) {
          callback(new Error('请选择大于开始日期的结束日期'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      regions: regionData,
      nextNodeNameContent: '负责图纸修改，核对清单数量',
      formDate: {
        projectInstruction: '',
        projectName: '',
        designUnit: '',
        suggestedUnit: '',
        projectType: [],
        emergencyLevel: '0',
        selectedRegions: [],
        beginTime: '',
        endTime: '',
        nextAuthor: [],
        remarks: '',
      },
      fileList: [],  // 原始上传文件对象
      fileListId: [],  // 得到上传文件的返回后的对象
      labelName: '',
      nextAuthorLists: [],
      projectTypeLists: [],
      selectedRegionsValue: [],
      ruleData: {
        projectInstruction: [
          { required: true, message: '请输入项目说明', trigger: 'blur' },
        ],
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
        ],
        designUnit: [
          { required: true, message: '请输入设计单位', trigger: 'blur' },
        ],
        suggestedUnit: [
          { required: true, message: '请输入建设说明', trigger: 'blur' },
        ],
        projectType: [
          { required: true, message: '请输入项目类型', trigger: 'change' },
        ],
        selectedRegions: [
          { required: true, message: '请输入地区', trigger: 'change' },
        ],
        beginTime: [
          {
            type: 'date',
            required: true,
            message: '请选择开始日期',
            trigger: 'change',
          },
        ],
        endTime: [
          { validator: checkEndTime, required: true, trigger: 'change' },
        ],
        nextAuthor: [{ required: true, message: '请选择下一流程人员', trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapGetters(['name', 'jobAccount', 'phone'])
  },
  mounted () {
    this.getNodeName()
    this.getProjectType()
  },
  methods: {
    // 文件操作
    beforeUpload (file) {
      // console.log(file)
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isLt2M = file.size / 1024 / 1024 < 500 //这里做文件大小限制

      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 500MB!',
          type: 'warning',
        })
      }
      return isLt2M
    },
    fnUploadRequest (file) {
      this.fileList.push(file.file)
    },
    onRemove (file, fileList) {
      this.fileList = fileList
    },
    async getFileId () {
      this.fileListId = []
      // console.log(this.fileList)
      const loading = this.$loading({
        lock: true,
        text: '文件上传提交中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (this.fileList.length > 0) {
        let formData = new FormData()
        this.fileList.forEach(item => {
          formData.append('file', item)
        })
        formData.append('userId', this.jobAccount)
        formData.append('businessId', 1)  // 1暂定为实施方案流
        formData.append('businessType', 1)   // 1代表创建流程页面
        await fileUploadFile(formData).then(res => {
          // console.log(res)
          if (res.code == 200) {
            if (res.data.length > 0) {
              res.data.forEach(item => {
                let obj = {}
                obj.id = item.id
                obj.fileName = item.fileName
                this.fileListId.push(obj)
                // setTimeout(() => {
                //   this.$message.success(item.fileName +'上传成功')
                // }, 500)
                loading.close()
              })
            }
          }
        })
      } else {
        loading.close()
      }
    },
    //
    regionChange (value) {
      let AreaCodeNode = this.$refs.cascaderAddr.getCheckedNodes()
      let AreaName = AreaCodeNode[0].pathLabels
      this.selectedRegionsValue = AreaName
    },
    // 人员
    handleChange (val) {
      this.labelName = getMultipleLabel(val, this.nextAuthorLists)
    },
    submit: _.debounce(async function () {
      await this.$refs.form.validate(async (valid) => {
        if (!valid) return false
        if (this.fileList.length == 0) {
          swal('错误', '未提交上传文件', 'warning')
          return false
        }
        let msg = '是否确认提交!'
        await this.confirm(msg, async () => {
          await this.getFileId()
          let params = {
            projectInstruction: this.formDate.projectInstruction,
            projectName: this.formDate.projectName,
            designUnit: this.formDate.designUnit,
            suggestedUnit: this.formDate.suggestedUnit,
            projectType: JSON.stringify(this.formDate.projectType),
            emergencyLevel: this.formDate.emergencyLevel,
            area: String(this.selectedRegionsValue),
            beginTime: this.formDate.beginTime,
            endTime: this.formDate.endTime,
            remarks1: this.formDate.remarks,
            status: 'current',
            type: '1',
            addName: this.name,
            currentNodeName: '1.0设计方案原资料',
            currentNodeID: 'T10002',
            jobAccount: this.jobAccount,
            nextNodeID: 'T10003',
            nodeTowardsInfo: nextNodeArr(this.jobAccount, this.formDate.nextAuthor, 'T10003', '2.0负责图纸修改', 'T10002', '1.0设计方案原资料'),
            file1: JSON.stringify(this.fileListId)
          }
          EmbodimentCreate(params)
            .then((res) => {
              if (res.code == 200) {
                this.alertok('创建成功', () => {
                  // 清除上传记录
                  this.fileList = []
                  this.$refs.upfile.clearFiles()
                  this.$router.go(-1)
                })
              } else {
                swal('错误', res.message || '网络连接错误', 'warning')
              }
            })
            .catch((err) => {
              swal('错误', '网络连接错误', 'error')
            })
        })
      })
    }, 800),
    Parent () {
      this.$router.go(-1)
    },
    // 获取人员
    getNodeName () {
      let params = {
        nodeID: 'T10003'
      }
      getAuthorByNodeID(params).then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.nextAuthorLists = res.data
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取项目类型
    getProjectType () {
      getAllProjectType().then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.projectTypeLists = res.data
        }
      }).catch((err) => { })
    }
  },
}
</script>
<style lang="less" scoped>
.headTitBox {
  display: flex;
  .ht {
    width: 33.3%;
    height: 30px;
    display: flex;
    justify-content: center;
    .ht_c {
      width: 80%;
      height: 30px;
      // background: red;
      display: flex;
      img {
        display: inline-block;
      }
      .ht_c_t {
        color: #2484FF;
        line-height: 30px;
        margin-left: 10px;
      }
    }
  }
  
}
.tit {
  font-weight: bold;
}
.form-content {
  .date,
  .el-select {
    width: 100%;
  }
  p {
    text-align: center;
    font-size: 30px;
    margin-bottom: 40px;
  }
  .form-input {
    width: 70%;
    // background-color: blue;
    margin: auto;
    .btn-option {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>